package container

import (
	"com.yy.api/common/logger"
	types "com.yy.api/common/pojo/models"
	"com.yy.api/common/utils"
	"strings"
)

type CreateContainerParam struct {
	RowImage     string              `json:"rowImage"`
	PortMappings []types.PortMapping `json:"portMappings"`
	GpuIds       []int               `json:"gpuIds"`
	Name         string              `json:"name"`
	UserId       string              `json:"userId"`
	DisplayId    string              `json:"displayId"`
}

func NewCreateContainerParam() CreateContainerParam {
	return CreateContainerParam{
		RowImage:     "",
		PortMappings: make([]types.PortMapping, 0),
		GpuIds:       make([]int, 0),
	}
}

func AssembleCreateContainerParam(rowImage string, portMappings []types.PortMapping, gpuIds []int, name, userId, displayId string) CreateContainerParam {
	return CreateContainerParam{
		RowImage:     rowImage,
		PortMappings: portMappings,
		GpuIds:       gpuIds,
		Name:         name,
		UserId:       userId,
		DisplayId:    displayId,
	}
}

func (p *CreateContainerParam) GetRowImage() string {
	return p.RowImage
}
func (p *CreateContainerParam) GetPortMappings() []types.PortMapping {
	return p.PortMappings
}
func (p *CreateContainerParam) GetGpuIds() []int {
	return p.GpuIds
}
func (p *CreateContainerParam) SetGpuIds(gpuIds []int) {
	p.GpuIds = gpuIds
}
func (p *CreateContainerParam) SetRowImage(rowImage string) {
	p.RowImage = rowImage
}

func (p *CreateContainerParam) SetPortMappings(portMappings []types.PortMapping) {
	p.PortMappings = portMappings
}

func ToParamPortMappings(portMappingsStr string) []types.PortMapping {
	if portMappingsStr == "" {
		return nil
	}
	splitChars := []string{
		",",
		":",
	}
	pmSlice := strings.Split(strings.TrimSpace(portMappingsStr), splitChars[0])
	var result []types.PortMapping
	for _, pm := range pmSlice {
		pSlice := strings.Split(pm, splitChars[1])
		hostPort := pSlice[0]
		containerPort := pSlice[1]
		result = append(result, types.PortMapping{
			HostPort:      hostPort,
			ContainerPort: containerPort,
		})
	}
	return result
}
func (p *CreateContainerParam) GetHostPorts() string {
	if len(p.PortMappings) > 0 {
		var hostPortList []string
		for _, portMapping := range p.PortMappings {
			hostPortList = append(hostPortList, portMapping.HostPort)
		}
		str, ok := utils.ObjToJsonStr(hostPortList)
		if !ok {
			logger.Default.Errorf("convert host port list failed!")
			return ""
		}
		return str
	}
	return ""
}
